package com.example.hhh.service.impl;

import com.example.hhh.model.Customer;
import com.example.hhh.repository.CustomerRepository;
import com.example.hhh.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

@Service
@Transactional
public class CustomerServiceImpl implements CustomerService {

    private final CustomerRepository customerRepository;

    @Autowired
    public CustomerServiceImpl(CustomerRepository customerRepository) {
        this.customerRepository = customerRepository;
    }

    @Override
    public Customer createCustomer(Customer customer) {
        return customerRepository.save(customer);
    }

    @Override
    public Customer getCustomerById(Integer id) {
        return customerRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("Customer not found with id: " + id));
    }

    @Override
    public Page<Customer> getAllCustomers(Pageable pageable) {
        return customerRepository.findAll(pageable);
    }

    @Override
    public Customer updateCustomer(Integer id, Customer customer) {
        Customer existing = getCustomerById(id);
        existing.setCustomerName(customer.getCustomerName());
        existing.setContactPhone(customer.getContactPhone());
        // 更新其他字段...
        return customerRepository.save(existing);
    }

    @Override
    public void deleteCustomer(Integer id) {
        customerRepository.deleteById(id);
    }

    @Override
    public List<Customer> searchCustomers(String keyword) {
        return customerRepository.findByCustomerNameContaining(keyword);
    }

    @Override
    public void importCustomers(List<Customer> customers) {
        customerRepository.saveAll(customers);
    }

    @Override
    public byte[] exportCustomers() {
        // 实现导出逻辑（如使用Apache POI）
        return new byte[0];
    }
}